<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ApiController;
use App\Models\Banner;
use App\Http\Requests\BannerRequest;
use App\Handlers\ImageUploadHandler;
use Validator;
use Auth;

class BannerController extends ApiController
{

    /**
     * banner 列表
     */
    public function index(Request $request) 
    {
        $limit = $request->input('size', 15);

        $orm = Banner::orderBy('sort','DESC');
        return $this->success($orm->paginate($limit));
    }

    /**
     * 获取指定幻灯片
     * 
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id) 
    { 
        return $this->success(Banner::find($id));
    }

    /**
     * 新建幻灯片
     * 
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(BannerRequest $request) 
    {
        $banner = Banner::create($request->all());
        return $this->message('幻灯片添加成功');
    }

    /**
     * 更新幻灯片
     * 
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update($id, BannerRequest $request) {
        Banner::where('id', $id)->update($request->all());

        return $this->message('幻灯片更新成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (Banner::destroy($id)) {
            return $this->message('删除成功');
        } else {
            return $this->failed('删除失败');
        }
    }

    /**
     * 上传幻灯片图片
     * 
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function imageUpload(Request $request, ImageUploadHandler $uploader)
    {
        if ($request->hasFile('banner-img')) {
            $result = $uploader->save($request->file('banner-img'), 'banner', Auth::guard('manager')->user()->id, 750);
            if ($result) {
                return $this->success($result);
            } else {
                return $this->failed('上传失败');
            }
        } else {
            return $this->failed('没有上传文件');
        }
    }

}
